import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps, withRouter } from 'react-router';
import UploadExample from '@/components/UploadPhotoExample';
import Upload from '@/components/Upload';
import Toast from '@/components/Toast';
import Input from '@/components/Input';
import {
  IDPlaceholderPre2,
  IDPlaceholderBg2,
  IDPlaceholderAvatar2
} from '@/components/Icon/IconC';
import { checkCardName, getQueryString, VALIDATES } from '@/common/utils';
import { TXInfoOfType } from '@/store/models/card';
import RSAEncrypt from '@/common/rsa-encrypt';
import md5 from 'md5';
import Services from './services';
import './index.less';
interface IAuthProps extends RouteComponentProps {
  TXInfo: TXInfoOfType;
  history: any;
  updateTXInfo: (payload: any) => Promise<any>;
}

interface IAuthState {
  identity1: string;
  identity2: string;
  crown: string;
  recordId: string;
  isAllUploaded: boolean;
}

const msg = {
  identity1: '请先上传身份证正面照',
  certNameNull: '请填写机主姓名',
  certNameError: '机主姓名限2~25位中文字符，请重新填写'
};
const imageMaxSize = 7;

class Auth extends PureComponent<IAuthProps, IAuthState> {
  constructor(props: IAuthProps) {
    super(props);
    this.state = {
      identity1: '',
      identity2: '',
      crown: '',
      recordId: getQueryString('recordId'),
      isAllUploaded: false
    };
  }

  componentDidMount() {
    if (!this.props.TXInfo.phone)
      this.props.history.replace(`/${window.location.search}`);
  }

  realNameInput = React.createRef<any>();

  // 姓名校验
  testName = (certName: any) => {
    if (!checkCardName(certName)) {
      Toast.show(VALIDATES['name'].error);
      return false;
    }
    return true;
  };

  /**
   * 上传API
   * @param imgBase64 上传照片 base64编码
   * @param imageType 照片标识: 1:身份证人像面照片; 2:身份证国徽面照片;3:免冠照（移动）
   */
  handleUploadIdentity = async (_fileFormData: FormData, imageType: any) => {
    const { phone } = this.props.TXInfo;
    let phoneNum = RSAEncrypt.encrypt(phone),
      t = new Date().getTime().toString();

    // 正面照上传
    if (imageType === 1) {
      // let _fileFormDataZ = new FormData();
      // _fileFormDataZ.append('file', _fileFormData.get('file') || '');
      // _fileFormDataZ.append('phoneNum', phoneNum);
      // _fileFormDataZ.append('t', t.toString());
      // let encStr = md5(`${phoneNum}${t}${RSAEncrypt.MD5KEY}`);
      // _fileFormDataZ.append('encStr', encStr);
      _fileFormData.append('phoneNum', phoneNum);
      _fileFormData.append('t', t.toString());
      let encStr = md5(`${phoneNum}${t}${RSAEncrypt.MD5KEY}`);
      _fileFormData.append('encStr', encStr);

      let res = (await Services.frontIdCardUpload(_fileFormData)) || {};
      let { certNo, certName, fileBase64 } = res;
      this.setState({
        identity1: fileBase64,
        identity2: '',
        crown: ''
      });
      this.props.updateTXInfo({
        certNoEnc: certNo,
        certNameEnc: certName
      });
    }

    // 反面照及免冠照上传
    if (imageType === 2 || imageType === 3) {
      const { certNameEnc, certNoEnc } = this.props.TXInfo;
      // let _formDataF = new FormData();
      // let certNo = RSAEncrypt.decrypt(certNoEnc);
      // let certName = RSAEncrypt.decrypt(certNameEnc);
      // let newCertNo = RSAEncrypt.encrypt(certNo);
      // let newCertName = RSAEncrypt.encrypt(certName);
      // _formDataF.append('file', _fileFormData.get('file') || '');
      // _formDataF.append('phoneNum', phoneNum);
      // _formDataF.append('certNo', newCertNo);
      // _formDataF.append('certName', newCertName);
      // _formDataF.append('t', t);
      // let encStr = md5(
      //   `${phoneNum}${newCertNo}${newCertName}${t}${RSAEncrypt.MD5KEY}`
      // );
      // _formDataF.append('encStr', encStr);
      let certNo = RSAEncrypt.decrypt(certNoEnc);
      let certName = RSAEncrypt.decrypt(certNameEnc);
      let newCertNo = RSAEncrypt.encrypt(certNo);
      let newCertName = RSAEncrypt.encrypt(certName);
      _fileFormData.append('phoneNum', phoneNum);
      _fileFormData.append('certNo', newCertNo);
      _fileFormData.append('certName', newCertName);
      _fileFormData.append('t', t);
      let encStr = md5(
        `${phoneNum}${newCertNo}${newCertName}${t}${RSAEncrypt.MD5KEY}`
      );
      _fileFormData.append('encStr', encStr);

      if (imageType === 2) {
        // 前置校验
        let encStrPre = md5(
          `${phoneNum}${newCertNo}${newCertName}${t}${RSAEncrypt.MD5KEY}`
        );
        let paramsPre = {
          phoneNum,
          certNo: newCertNo,
          certName: newCertName,
          t: t,
          encStr: encStrPre
        };

        let preValRes = await Services.preReverseCheck(paramsPre);
        if (!preValRes) return;

        let res = await Services.reverseIdCardUpload(_fileFormData);
        if (!res) return;
        this.setState({
          identity2: res.fileBase64,
          crown: ''
        });
      }
      if (imageType === 3) {
        let res = await Services.bareheadedPhotoUpload(_fileFormData);
        if (!res) return;
        this.setState({
          crown: res.fileBase64,
          isAllUploaded: true
        });
      }
    }
  };

  handleClickAction = () => {
    const { identity1, identity2, crown } = this.state;
    let isEnabledNextPath = identity1 && identity2 && crown;
    if (!isEnabledNextPath) return;
    this.props.history.replace(`/livingInfo${window.location.search}`);
  };

  handleClearAction = () => {
    this.props.updateTXInfo({
      certNameEnc: ''
    });
  };

  render() {
    const { identity1, identity2, crown, isAllUploaded } = this.state;
    const {
      certNameEnc,
      certNoEnc,
      userNameFromBoss,
      certNumFromBoss
    } = this.props.TXInfo;
    let isEnabledNextPath = identity1 && identity2 && crown;
    // 解密脱敏处理 用户身份证号
    let certNo = RSAEncrypt.decrypt(certNoEnc) || '',
      certName = RSAEncrypt.decrypt(certNameEnc) || '';
    // let certNoDecense = certNo.replace(/^(.{6})(?:\d+)(.{4})$/, '$1***$2');
    // console.log(
    //   '%c [ certNoDecense ]',
    //   'font-size:13px; background:pink; color:#bf2c9f;',
    //   certNoDecense
    // );
    return (
      <div className="auth">
        <div className="auth-info">
          <p className="auth-info-desc">请使用{userNameFromBoss}身份证</p>
          <p className="auth-info-desc">{certNumFromBoss} 进行认证</p>
        </div>
        <div className="auth-upload-container-b">
          <div className="auth-upload-container">
            {/* 照片示例 */}
            <UploadExample cls="auth-upload-container-example" />

            <p className="maininfo-desc">请按以下顺序依次上传照片：</p>
            <div className="upload_components_wrap">
              {/* 身份证正面照 */}
              <Upload
                defaultBg={IDPlaceholderPre2({
                  margin: '0',
                  width: 'auto',
                  height: 'auto'
                })}
                imageMaxSize={imageMaxSize}
                defaultText={
                  identity1 ? '点击可重新上传' : '点击上传身份证正面'
                }
                clearUploadInfo={isAllUploaded}
                imgBase64={identity1}
                uploadMethod={(_fileFormData: FormData) => {
                  return this.handleUploadIdentity(_fileFormData, 1);
                }}
                inputDisable={isAllUploaded}
                disabledClickAction={() => {
                  if (isAllUploaded)
                    return Toast.show(
                      '您已经成功上传实名制信息，无需重新上传，请继续完成活体认证'
                    );
                }}
              />

              {/* 身份证反面照 */}
              <Upload
                defaultBg={IDPlaceholderBg2({
                  margin: '0',
                  width: 'auto',
                  height: 'auto'
                })}
                imageMaxSize={imageMaxSize}
                defaultText={
                  identity2 ? '点击可重新上传' : '点击上传身份证反面'
                }
                clearUploadInfo={isAllUploaded}
                imgBase64={identity2}
                inputDisable={
                  isAllUploaded ||
                  !identity1 ||
                  !VALIDATES['name'].reg.test(certName) ||
                  !VALIDATES['idCard'].reg.test(certNo)
                }
                disabledClickAction={() => {
                  if (isAllUploaded)
                    return Toast.show(
                      '您已经成功上传实名制信息，无需重新上传，请继续完成活体认证'
                    );
                  if (!identity1) {
                    Toast.show(msg['identity1'], 1);
                    return;
                  }
                  if (!this.testName(certName)) return;
                  if (!VALIDATES['idCard'].reg.test(certNo))
                    return Toast.show(VALIDATES['idCard'].error);
                }}
                uploadMethod={async (formData: any) => {
                  return this.handleUploadIdentity(formData, 2);
                }}
              />

              {/* 身份证免冠照 */}
              <Upload
                defaultBg={IDPlaceholderAvatar2({
                  margin: '0',
                  width: 'auto',
                  height: 'auto'
                })}
                defaultText={'点击上传正面免冠照片'}
                clearUploadInfo={isAllUploaded}
                imgBase64={crown}
                imageMaxSize={imageMaxSize}
                inputDisable={isAllUploaded || !identity1 || !identity2}
                uploadMethod={async (formData: any) => {
                  return await this.handleUploadIdentity(formData, 3);
                }}
                disabledClickAction={() => {
                  if (isAllUploaded)
                    return Toast.show(
                      '您已经成功上传实名制信息，无需重新上传，请继续完成活体认证'
                    );
                  Toast.show('请先上传身份证正反面照');
                }}
              />
            </div>

            <div className="auth-upload-container-maininfo">
              <p className="auth-upload-container-maininfo-desc">
                请上传与以下身份信息匹配的证件：
              </p>
              <div className="auth-upload-container-maininfo-item">
                <span className="auth-upload-container-maininfo-item-label">
                  机主姓名
                </span>
                <Input
                  placeholder="上传身份证正面后获取"
                  type="text"
                  className={`auth-upload-container-maininfo-item-ipt ${
                    !identity1 || !!identity2 ? 'disabled' : ''
                  } `}
                  disabled={!identity1 || !!identity2}
                  ref={'realNameInput'}
                  value={certName}
                  onChange={(e: any) => {
                    if (!identity1 || !!identity2) return;
                    this.props.updateTXInfo({
                      certNameEnc: RSAEncrypt.encrypt(e.target.value)
                    });
                  }}
                  onBlur={(e: any) => {
                    this.testName(e.target.value);
                  }}
                />
                {certName && identity1 && !identity2 && (
                  <span
                    className="auth-upload-container-maininfo-item-clear-icon"
                    onClick={this.handleClearAction}
                  ></span>
                )}
              </div>
              <div className="auth-upload-container-maininfo-item">
                <span className="auth-upload-container-maininfo-item-label">
                  身份证号
                </span>
                <Input
                  placeholder="上传身份证正面后获取"
                  type="text"
                  className={`auth-upload-container-maininfo-item-ipt ${
                    !identity1 || !!identity2 ? 'disabled' : ''
                  }`}
                  disabled={!identity1 || !!identity2}
                  value={certNo}
                  onChange={(evt: any) => {
                    if (!identity1 || !!identity2) return;
                    this.props.updateTXInfo({
                      certNoEnc: RSAEncrypt.encrypt(evt.target.value)
                    });
                  }}
                  onBlur={(e: any) => {
                    let idCard = e.target.value;
                    if (!idCard) return Toast.show(VALIDATES['idCard'].empty);
                    if (!VALIDATES['idCard'].reg.test(idCard))
                      return Toast.show(VALIDATES['idCard'].error);
                  }}
                />
              </div>
            </div>
          </div>
        </div>
        <div
          className={`auth-btn confirm-wrapper-btn ${
            isEnabledNextPath ? '' : 'grey'
          }`}
          onClick={this.handleClickAction}
        >
          下一步
        </div>
      </div>
    );
  }
}

const mapState = ({ CardReSold }: any) => ({
  TXInfo: CardReSold.TXInfo
});

// @ts-ignore
const mapDispath = ({ CardReSold }) => ({
  updateTXInfo: CardReSold.updateTXInfo
});

// @ts-ignore
export default connect(mapState, mapDispath)(withRouter(Auth));
